<template>
    <el-card style="min-height: 100vh;">
        <!-- 标题部分 -->
        <div class="box">
            <div class="short"></div>

            <div>{{ route.query._id ? '编辑机构信息' : '新增机构信息' }}</div>
        </div>
        <div style="margin:15px 25px 30px">机构信息</div>
        <!-- 表单部分 -->
        <el-form ref="agencyFormRef" :model="AgencyInfo" :rules="rules" label-width="100px" style="margin-top: 20px">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="机构编号">
                        <el-input v-model="AgencyInfo._id" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="机构名称" prop="name">
                        <el-input v-model="AgencyInfo.name" placeholder="请输入机构名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="机构图片">
                        <el-upload class="avatar-uploader" :action="`${baseURL}/images/upload`" :show-file-list="false"
                            :on-success="handleAvatarSuccess">
                            <img v-if="AgencyInfo.image" :src="AgencyInfo.image" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="联系人姓名">
                        <el-input v-model="AgencyInfo.contacts" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="联系电话">
                        <el-input v-model="AgencyInfo.phone" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="18">
                    <el-form-item label="机构地址" prop="address">
                        <el-input v-model="AgencyInfo.address" type="textarea" placeholder="请输入" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="18">
                    <el-form-item label="机构介绍">
                        <el-input v-model="AgencyInfo.intro" type="textarea" placeholder="请输入" :rows="5" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="primary" @click="handleSave">保存</el-button>
                        <el-button @click="$router.back">返回</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </el-card>
</template>

<script setup>
import { reactive, ref , onMounted} from 'vue';
import { useRoute } from 'vue-router';
import { Plus } from '@element-plus/icons-vue'
import { addAgencyApi, getAgencyInfoApi, updateAgencyApi } from '../../../api/agency';

const baseURL = import.meta.env.VITE_BASE_URL
// 路由实例，用于获取编辑的id
const route = useRoute()
// 判断是否为编辑状态（有id则为编辑）
const isEdit = ref(!!route.query._id)


// 表单引用
const agencyFormRef = ref(null)

// 表单数据
const AgencyInfo = ref({})

// 上传头像成功回调
const handleAvatarSuccess = (res) => {
    if (res.code == 200) {
        AgencyInfo.value.image = res.data
    }
}

const rules = reactive({
    name: [
        { required: true, message: '请输入机构名称', trigger: 'blur' },
        { min: 2, message: '至少包含两个字符', trigger: 'blur' }
    ],
    address: [
        { required: true, message: '请输入机构地址', trigger: 'blur' },
        { min: 2, message: '至少包含两个字符', trigger: 'blur' }
    ]

})
//
// 获取医生详情（编辑时用）
const getAgency = async (id) => {
    try {
        const res = await getAgencyInfoApi({ _id: id })
        if (res.code === 200) {
            const Agency = res.data
           
            AgencyInfo.value = {
                _id:Agency._id,
                image:Agency.image,
                name:Agency.name,
                contacts: Agency.contacts,
                phone:Agency.phone,
                address:Agency.address,
                intro:Agency.intro,
            }
        }
    } catch (err) {
        console.error('获取医生详情失败：', err)
        ElMessage.error('加载编辑数据失败')
    }
}
//点击保存逻辑
const handleSave = () => {
    agencyFormRef.value.validate((valid) =>{
        if (valid){
           
            //进入if，说明是在修改
            if (route.query._id){
                updateAgencyApi({
                    ...AgencyInfo.value
                })
                .then(res =>{
                    if(res.code == 200){
                        ElMessage.success('修改成功！')
                    }
                })
            }else{
                addAgencyApi({
                    ...AgencyInfo.value
                })
                .then(res =>{
                    if(res.code == 200){
                        ElMessage.success('新增成功！')
                        AgencyInfo.value = {
                            _id:'',
                            image: '',
                            name: '',
                            contacts: '',
                            phone: '',
                            address: '',
                            intro: '',
                        }
                    }
                }).catch(res => {
                    ElMessage.warning(res.message)
                })
            }
        } else {
            ElMessage.error('表单验证失败，请检查必填项')
            return false
        }
    })
}

onMounted(()=>{
    //进入if说明是编辑，则发送请求回显
    if (isEdit.value){
        getAgency(route.query._id)
    }
})

</script>

<style scoped lang="scss">
.big-card {
    min-height: 100vh;
}

.teamInfo-container {
    span {
        margin: 20px 0;
    }
}

.info-box {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    border-bottom: 1px #eee solid;

    span {
        font-size: 13px;
        color: #999999;
    }

    input {
        border: 1px #ddd solid;
        border-radius: 5px;
        width: 200px;
        height: 35px;
        margin-left: 15px;
        padding-left: 20px;

        &::-webkit-input-placeholder {
            /* Chrome/Safari */
            color: #999;
            font-size: 14px;
        }
    }
}

.avatar-uploader {
    width: 60px;
    height: 60px;
    border-radius: 8px;
    border: 1px dashed var(--el-border-color);
    text-align: center;
    cursor: pointer;

    .avatar {
        width: 100%;
        height: 100%;
        border-radius: 8px;
    }

    .el-icon.avatar-uploader-icon {
        font-size: 20px;
        color: #5f90d4;
        width: 60px;
        height: 60px;
        text-align: center;
    }

}
</style>